package com.yanqu.road.server.logic.activity.condition.normal;

import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.mall.MallActivityInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.config.patrons.PatronsBreak;
import com.yanqu.road.entity.config.patrons.PatronsInfo;
import com.yanqu.road.entity.enums.eActivityConfigType;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.player.UserBeauty;
import com.yanqu.road.entity.player.UserMallBuyCount;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityMallModule;
import com.yanqu.road.server.gameplayer.module.activity.fund.ActivityFundModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.BeautyModule;
import com.yanqu.road.server.gameplayer.module.task.TaskModule;
import com.yanqu.road.server.logic.activity.BaseActivityData;
import com.yanqu.road.server.logic.activity.condition.BaseActivityCondition;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.MallActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.PatronsMgr;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *  新首充-现金
 */
public class NewFirstRechargeCash2024Condition extends BaseActivityCondition {

	public NewFirstRechargeCash2024Condition(ActivityInfo activityInfo, ActivityConditionInfo activityConditionInfo, BaseActivityData baseActivityData) {
		super(activityInfo, activityConditionInfo, baseActivityData);
	}

	@Override
	public void addTrigger(GamePlayer player) {
		player.getModule(TaskModule.class).getGameEvent().addListener(eGamePlayerEventType.FirstRechargeCash2024.getValue(), handle);
	}

	@Override
	public void removeTrigger(GamePlayer player) {
		player.getModule(TaskModule.class).getGameEvent().removeListener(eGamePlayerEventType.FirstRechargeCash2024.getValue(), handle);
	}

	private boolean checkBuyMallInfo() {
		List<BigInteger> paramList = getActivityConditionInfo().getParamList();
		int mallKey = paramList.get(0).intValue();
		if (mallKey != 0) {
			// 付费
			MallInfo mallInfo = NormalActivityMgr.getRMBActivityMallInfoByGrade(activityConditionInfo.getActivityId(), mallKey);
			if (mallInfo == null) {
				return false;
			}
			return player.getModule(ActivityFundModule.class).isBuy(mallInfo);
		}
		return true;
	}

	public boolean isCompleted(GamePlayer player) {
		int mallKey = activityConditionInfo.getParamList().get(0).intValue();
		int checkDay = activityConditionInfo.getParamList().get(3).intValue();
		//获取礼包详情
		MallActivityInfo mallActivityInfo = MallActivityMgr.getInTimeActivity(this.activityInfo.getActivityId());
		if (mallActivityInfo == null || mallActivityInfo.getMallInfoMap() == null) {
			return false;
		}

		MallInfo targetMallInfo = NormalActivityMgr.getRMBActivityMallInfoByGrade(activityConditionInfo.getActivityId(), mallKey);
		if (targetMallInfo == null) {
			return false;
		}
		//断礼包是否购买
		UserMallBuyCount userMallBuyCount = player.getModule(ActivityMallModule.class).getUserMall(targetMallInfo.getMallId());
		if (userMallBuyCount == null) {
			return false;
		}
		if (userMallBuyCount.getActivityId() != this.activityInfo.getActivityId()) {
			return false;
		}
		if (userMallBuyCount.getCount() <= 0) {
			return false;
		}
		//判断天数是否符合
		long buyMallTime = userMallBuyCount.getLastUpdateTime();
		long todayZero = DateHelper.getTodayZeroTimeStamp();
		long rechargeDayZero = DateHelper.getZeroTimeStamp(buyMallTime * 1000);
		long day = (todayZero - rechargeDayZero) / DateHelper.DAY_MILLIONS + 1;
        //返回
		return day >= checkDay;
	}

	@Override
	protected void player_BoardLevelHandle(Object object) {

	}

	@Override
	public String getReward() {
		int patronsId = 0;
		int level = 0;
		boolean needBreak = false;
		String transformItem = null;//配置格式：门客ID或者美女ID#道具ID=道具数量
		List<Integer> repeatedIds = new ArrayList<>();
		//首充、镖师
		if (this.activityInfo.getType() == eActivityType.NewFirstRecharge2024.getValue()) {
			Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(this.activityInfo.getActivityId());
			if (activityConfigMap != null && activityConfigMap.containsKey(eActivityConfigType.RECHARGE_REWARD_PATRONS_LEVEL.getName())) {
				List<Integer> paramList = StringUtils.stringToIntegerList(activityConfigMap.get(eActivityConfigType.RECHARGE_REWARD_PATRONS_LEVEL.getName()).getValue(), "\\|");
				patronsId = paramList.get(0);
				level = paramList.get(1);
				needBreak = paramList.size() == 3 && paramList.get(2) == 1;
				if (activityConfigMap.containsKey("REWARD_PATRONS_TRANSFORM_ITEM")) {
					transformItem = activityConfigMap.get("REWARD_PATRONS_TRANSFORM_ITEM").getValue();
					repeatedIds = findRepeatTransformId(transformItem);
				}
			}
		}

		boolean needTransFormBeauty = false;
		boolean needTransFormPatrons = false;
		for (Integer repeatedId : repeatedIds) {
			UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(repeatedId);
			if (userPatrons != null) {
				needTransFormPatrons = true;
			}

			UserBeauty userBeauty = player.getModule(BeautyModule.class).getUserBeauty(repeatedId);
			if (userBeauty != null) {
				needTransFormBeauty = true;
			}
		}


		String reward = super.getReward();
		try {
			//首充、镖师
			Property property = PropertyHelper.parseStringToProperty(reward);
			for (Map.Entry<Integer, BigInteger> entry : property.getGoods().entrySet()) {
				int itemId = entry.getKey();
				if ((GoodsMgr.isPatronsGoods(itemId) && needTransFormPatrons )
						|| (GoodsMgr.isBeautyGoods(itemId) && needTransFormBeauty)){
					if (repeatedIds.contains(itemId) && !StringUtils.isNullOrEmpty(transformItem)) {//之前已有门客/美女,转换奖励
						String transformReward = findTransformReward(transformItem, itemId);
						if (!StringUtils.isNullOrEmpty(transformReward)) {
							//发邮件
							transformSendMail(transformReward, itemId);
						}
					}
				}

				//奖励有该门客
				if (itemId == patronsId && GoodsMgr.isPatronsGoods(itemId) && !needTransFormPatrons) { //没转换的才升级
					PatronsInfo patronsInfo = PatronsMgr.getPatronsInfo(itemId);
					UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(patronsInfo.getId());
					if (userPatrons != null) {
						//门客等级
						if (level > userPatrons.getLevel()) {
							userPatrons.setLevel(level);
						}
						//突破等级
						int breakLv = 0;
						for (int i = 0; i < 500; i++) {
							PatronsBreak patronsBreak = PatronsMgr.getPatronsBreak(i);
							if (patronsBreak == null) {
								continue;
							}
							if (level >= patronsBreak.getCurrentMaxLv()) {
								breakLv = i;
							} else {
								if (needBreak) {
									breakLv = i;
								}
								break;
							}
						}
						if (breakLv > userPatrons.getBreakLv()) {
							userPatrons.setBreakLv(breakLv);
						}
						player.getModule(PatronsModule.class).syncPatronsData(userPatrons);

						player.getModule(PatronsModule.class).refreshCopyMaxPatronsLevel(false);
						break;
					}
				}

			}
		} catch (Exception e) {
			logger.info("activity {} player {} recharge reward {} special handle error", this.activityInfo.getActivityId(), player.getUserId(), reward);
		}
		return reward;
	}


	/**
	 * 配置格式：门客ID或者美女ID#道具ID=道具数量
	 *
	 * @param transformStr
	 * @return
	 */
	private static String findTransformReward(String transformStr, int findId) {
		for (String str : transformStr.split("\\|")) {
			String[] split = str.split("#");
			if (split.length != 2) {
				return null;
			}
			int checkId = Integer.parseInt(split[0]);
			String reward = split[1];
			if (checkId == findId) {
				return reward;
			}
		}
		return null;
	}

	private static List<Integer> findRepeatTransformId(String transformStr) {
		List<Integer> list = new ArrayList<>();
		for (String str : transformStr.split("\\|")) {
			String[] split = str.split("#");
			if (split.length != 2) {
				return null;
			}
			int checkId = Integer.parseInt(split[0]);
			list.add(checkId);
		}
		return list;
	}

	private void transformSendMail(String reward, int transformId) {
		String activityName = ServerLanguageMgr.getContent(activityInfo.getActivityName(), player.getLanguage());
		String mailTitle = MultipleLanguageMgr.getContent("GOODS_AUTO_TRANSFORM_TITLE", player.getLanguage());


		String transformName = "";
		if (GoodsMgr.isPatronsGoods(transformId)) {
			transformName = MultipleLanguageMgr.getContent("Patrons-" + transformId, player.getLanguage());
		}else {
			transformName = MultipleLanguageMgr.getContent("Beauty-" + transformId, player.getLanguage());
		}

		String mailContent = StringUtils.format(MultipleLanguageMgr.getContent("GOODS_AUTO_TRANSFORM_CONTENT", player.getLanguage()), activityName, transformName);

		MailManager.sendMail(player.getUserId(), eMailType.SYSTEM.getValue(), reward, mailContent, mailTitle);
	}
}
